import { login, logout, getInfo } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";
import MD5 from "md5";

const user = {
  state: {
    token: getToken(),
    name: "",
    avatar: "",
    roles: [],
    permissions: [],
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password1 = userInfo.password.trim();
      const password = MD5(`${MD5(password1)}oneninesix`);
      return new Promise((resolve, reject) => {
        login(username, password)
          .then((res) => {
            if (res.code != "200") {
              this.$message.error(res.info);
            } else {
              setToken(res.data.token);
              commit("SET_TOKEN", res.data.token);
              resolve(res);
            }
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        // getInfo().then(res => {
        //   const user = res.user
        //   const avatar = user.avatar == "" ? require("@/assets/images/profile.jpg") : process.env.VUE_APP_BASE_API + user.avatar;
        //   if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
        //     commit('SET_ROLES', res.roles)
        //     commit('SET_PERMISSIONS', res.permissions)
        //   } else {
        //     commit('SET_ROLES', ['ROLE_DEFAULT'])
        //   }
        //   commit('SET_NAME', user.userName)
        //   commit('SET_AVATAR', avatar)
        //   resolve(res)
        // }).catch(error => {
        //   reject(error)
        // })
        let res = {
          user: {
            admin: true,
            avatar: "",
            createBy: "admin",
            createTime: "2021-09-09 17:25:28",
            delFlag: "0",
            dept: {
              ancestors: null,
              children: [],
              createBy: null,
              createTime: null,
              delFlag: null,
              deptId: 103,
              deptName: "研发部门",
              email: null,
              leader: "元数据",
              orderNum: "1",
              params: {},
              parentId: 101,
              parentName: null,
              phone: null,
              remark: null,
              searchValue: null,
              status: "0",
              updateBy: null,
              updateTime: null,
            },
            deptId: 103,
            email: "ry@163.com",
            loginDate: "2021-12-07T11:03:42.669+0800",
            loginIp: "222.128.26.253",
            nickName: "元数据",
            params: {},
            phonenumber: "15888888888",
            postIds: null,
            remark: "管理员",
            roleId: null,
            roleIds: null,
            roles: [
              {
                admin: true,
                createBy: null,
                createTime: null,
                dataScope: "1",
                delFlag: null,
                deptCheckStrictly: false,
                deptIds: null,
                flag: false,
                menuCheckStrictly: false,
                menuIds: null,
                params: {},
                remark: null,
                roleId: 1,
                roleKey: "admin",
                roleName: "超级管理员",
                roleSort: "1",
                searchValue: null,
                status: "0",
                updateBy: null,
                updateTime: null,
              },
            ],
            searchValue: null,
            sex: "1",
            status: "0",
            updateBy: null,
            updateTime: null,
            userId: 1,
            userName: "admin",
          },
        };
        const user = res.user;
        const avatar =
          user.avatar == ""
            ? require("@/assets/images/profile.jpg")
            : process.env.VUE_APP_BASE_API + user.avatar;
        if (res.roles && res.roles.length > 0) {
          // 验证返回的roles是否是一个非空数组
          commit("SET_ROLES", res.roles);
          commit("SET_PERMISSIONS", res.permissions);
        } else {
          commit("SET_ROLES", ["ROLE_DEFAULT"]);
        }
        commit("SET_NAME", user.userName);
        commit("SET_AVATAR", avatar);
        resolve(res);
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      // return new Promise((resolve, reject) => {
      //   logout(state.token).then(() => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_PERMISSIONS", []);
      removeToken();
      //     resolve();
      //   }).catch(error => {
      //     reject(error)
      //   })
      // });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise((resolve) => {
        commit("SET_TOKEN", "");
        removeToken();
        resolve();
      });
    },
  },
};

export default user;
